<template>
  <div class="login-container">
    <div class="login-weaper animated bounceInDown">
      <div class="login-left">
        <img class="img"
             :src="logoUrl"
             alt="">
        <p class="title">{{fullName}}</p>
      </div>
      <div class="login-border">
        <div class="login-main">
          <a-form :form="form"  class="login-form" ref="formLogin" id="formLogin" v-show="showLoginBox">
            <a-tabs
              :activeKey="customActiveKey"
              :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
              @change="handleTabClick">
              <a-tab-pane key="tab1" :tab="$t('m.system.login.other.login_type1')">
                <div v-if="demo">
                  <p>{{$t('m.system.login.other.admin_account')}}：admin/admin</p>
                  <p>{{$t('m.system.login.other.general_account')}}：zhangs/123456</p>
                </div>
                <a-form-item>
                  <a-input
                    size="large"
                    v-decorator="['username',{initialValue:username, rules: validatorRules.username.rules}]"
                    type="text"
                    :placeholder="$t('m.system.login.entity.username')">
                    <ych-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>
                <a-form-item>
                  <a-input
                    v-decorator="['password',{initialValue:password, rules: validatorRules.password.rules}]"
                    size="large"
                    type="password"
                    autocomplete="false"
                    :placeholder="$t('m.system.login.entity.password')">
                    <ych-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>
                <a-form-item v-if="isOpenCode">
                    <div style="display: flex;align-items: center;">
                        <a-input
                            v-decorator="['passcode',{initialValue:passcode, rules: validatorRules.passcode.rules}]"
                            size="large"
                            type="number"
                            autocomplete="false"
                            placeholder="请输入验证码">
                            <ych-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                        </a-input>
                        <a-button 
                        class="code-btn-box"
                        style="margin-left: 15px;"
                        size="large" 
                        @click.stop.prevent="getCode(hourString,minuteString,secondString)">
                          <span class="code-text" v-if="!totalSeconds">{{codeText}}</span>
                          <span class="code-text" v-if="hourString == '00' && minuteString == '00' && secondString == '00' && totalSeconds && !isGetCode ">重新获取验证码</span>
                          <span class="code-text text-color" v-if="hourString !== '00'">{{hourString+'：'+minuteString+'：'+secondString}}</span>
                          <span class="code-text text-color" v-else-if="minuteString !== '00'">{{minuteString+'：'+secondString}}</span>
                          <span class="code-text text-color" v-else-if="secondString !== '00'">{{secondString}}</span>
                        </a-button>
                    </div>
                    
                </a-form-item>
              </a-tab-pane>
              <!-- <a-tab-pane key="tab2" :tab="$t('m.system.login.other.login_type2')">
                <a-form-item>
                  <a-input
                    v-decorator="['mobile',validatorRules.mobile]"
                    size="large"
                    type="text"
                    :placeholder="$t('m.system.login.entity.mobile')">
                    <ych-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>

                <a-row :gutter="16">
                  <a-col class="gutter-row" :span="16">
                    <a-form-item>
                      <a-input
                        v-decorator="['captcha',validatorRules.captcha]"
                        size="large"
                        type="text"
                        :placeholder="$t('m.system.login.entity.captcha')">
                        <ych-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                      </a-input>
                    </a-form-item>
                  </a-col>
                  <a-col class="gutter-row" :span="8">
                    <a-button
                      class="getCaptcha"
                      tabindex="-1"
                      :disabled="state.smsSendBtn"
                      @click.stop.prevent="getCaptcha"
                      v-text="!state.smsSendBtn && $t('m.system.login.other.getCaptcha') || (state.time+' s')"></a-button>
                  </a-col>
                </a-row>
              </a-tab-pane> -->
            </a-tabs>

            <!-- <a-form-item>
              <a-select v-if="lang_enable" v-model="language" @change="changeLanguage" :options="lang" style="width: 120px;"></a-select>
              //<a-checkbox v-decorator="['rememberMe', {initialValue: true, valuePropName: 'checked'}]">自动登录</a-checkbox>
              <router-link :to="{ name: 'alteration'}" class="forge-password" style="float: right;">
                {{$t('m.system.login.other.alteration')}}
              </router-link>
              <router-link :to="{ name: 'register'}" class="forge-password" style="float: right;margin-right: 10px">
                {{$t('m.system.login.other.register')}}
              </router-link>
            </a-form-item> -->

            <a-form-item>
              <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-submit"
                :loading="loginBtn"
                @click.stop.prevent="handleSubmit"
                :disabled="loginBtn">{{$t('m.system.login.other.loginBtn')}}
              </a-button>
            </a-form-item>

          </a-form>

          <div v-show="!showLoginBox" id="login_container"></div>
          <div v-if="showDingtalk" class="login-other">
            <span>其他登录方式</span>
            <a v-if="showDingtalk" @click="useDingtalk" title="钉钉">
              <a-icon class="item-icon" type="dingding"></a-icon>
            </a>
            <a v-if="!showLoginBox" @click="showLoginBox = true" title="返回默认登录">
              <a-icon class="item-icon" type="windows"></a-icon>
            </a>
          </div>

          <a-modal
            :maskClosable="false"
            :keyboard="false"
            :title="$t('m.system.login.other.deptSelect')"
            :width="450"
            :visible="departVisible"
            :closable="false">

            <template slot="footer">
              <a-button type="primary" @click="departOk">{{ $t('m.common.button.ok') }}</a-button>
            </template>

            <a-form>
              <a-form-item
                :labelCol="{span:4}"
                :wrapperCol="{span:20}"
                style="margin-bottom:10px"
                :validate-status="validate_status">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span>{{$t('m.system.portal.other.deptselect_tip')}}</span>
                  </template>
                  <a-avatar style="backgroundColor:#87d068" icon="gold"/>
                </a-tooltip>
                <a-select @change="departChange" :class="{'valid-error':validate_status=='error'}" :placeholder="$t('m.system.login.other.deptSelect')"
                          style="margin-left:10px;width: 80%">
                  <ych-icon slot="suffixIcon" type="gold"/>
                  <a-select-option
                    v-for="d in departList"
                    :key="d.id"
                    :value="d.orgCode">
                    {{ d.orgName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-modal>

          <Verify
            @success="login"
            captchaType="blockPuzzle"
            ref="verify"
          ></Verify>

        </div>

      </div>
    </div>
  </div>
</template>

<script>
  import TwoStepCaptcha from './TwoStepCaptcha'
  import { mapActions } from 'vuex'
  import { putAction, postAction, getSmsCode, validateLoginCode, getEnableSmsValidate } from '@/api/manage'
  import store from '@/store/'
  import Verify from '../../../components/verifition/Verify'
  import YchConstant from "@/api/YchConstant";
  import {SSO} from "../../../sso/SSO";
  import config from '@/settings'
  import TokenStorageUtil from "../../../utils/TokenStorageUtil";

  export default {
    name: 'Login',
    components: {
      TwoStepCaptcha,
      Verify
    },
    data () {
      return {
        language: store.getters.language,
        lang: YchConstant.LANG,
        lang_enable: bootConfig[process.env.NODE_ENV].VUE_APP_LOCALE_ENABLE || false,
        logoUrl: window._CONFIG.logo_url || process.env.BASE_URL + 'logo.svg',
        customActiveKey: 'tab1',
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        stepCaptchaVisible: false,
        form: this.$form.createForm(this),
        encryptedString: {
          key: '',
          iv: '',
        },
        state: {
          time: 60,
          smsSendBtn: false,
        },
        departList: [],
        departVisible: false,
        departSelected: '',
        currentUsername: '',
        validate_status: '',
        username: window.isDemo ? 'admin' : null,
        password: window.isDemo ? 'admin' : null,
        demo: window.isDemo,
        showLoginBox: true,
        showDingtalk: false,
        codeText:'获取验证码',
        isOpenCode:false,
        totalSeconds:null,//总秒数
        hour:0,
        minute:0,
        second:0,
        timer: '',
        isGetCode:false,
        passcode:null,
      }
    },
    computed:{
      validatorRules() {
        return {
          username: {
            rules: [{
              required: true,
              message: this.$t('m.common.tip.verify_required')
            }, {validator: this.handleUsernameOrEmail}]
          },
          password: {rules: [{required: true, message: this.$t('m.common.tip.verify_required'), validator: 'click'}]},
          passcode: {
            rules: [{
              required: true,
              message: '请输入验证码',
            }]
          },
          mobile: {
            rules: [{
              required: true,
              message: this.$t('m.common.tip.verify_required')
            }, {validator: this.validateMobile}]
          },
          captcha: {rules: [{required: true, message: this.$t('m.common.tip.verify_required')}]},
        }
      },
      fullName(){
        const name = window._CONFIG.full_name  || this.$t('m.logo.full_name')
        document.title = name;
        return name;
      },
      hourString () {
          return this.formatNum(this.hour)
      },
      minuteString () {
          return this.formatNum(this.minute)
      },
      secondString () {
          return this.formatNum(this.second)
      }
    },
    created () {
      getEnableSmsValidate().then(res=>{
            if(res.code == 200){
                this.isOpenCode = res.result.flag
            }else{
                this.isOpenCode = false
                this.$message.warning(res.message)
            }
        })
      TokenStorageUtil.remove()
      this.getRouterData()
      this.showDingtalk = !!(bootConfig[process.env.NODE_ENV].VUE_APP_DINGTALK_APP_KEY) && config.showDingtalk;
    },
    methods: {
      ...mapActions(['Login', 'Logout', 'PhoneLogin', 'ThirdLogin']),
      changeLanguage(language){
        this.language = language
        this.$store.dispatch('setLanguage', {language, i18n: this.$i18n})
      },
      // handler
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      handleTabClick (key) {
        this.customActiveKey = key
      },
      //获取验证码
      getCode(){
          if(this.isGetCode && this.second){
            return false
          }
          this.form.validateFields(['username', 'password'], { force: true }, (err, values) => {
              //console.log(err)
            if (!err) {
              let loginParams = {
                  username:values.username,
                  password:values.password,
              }
              //console.log(loginParams)
              getSmsCode(loginParams).then(res=>{
                  if(res.code == 200){
                      this.totalSeconds = Number(res.result.djs)
                      if (this.totalSeconds > 0) {
                          this.hour = Math.floor((this.totalSeconds / 3600) % 24)
                          this.minute = Math.floor((this.totalSeconds / 60) % 60)
                          this.second = Math.floor(this.totalSeconds % 60)
                          this.countDowm()
                      }
                      this.isGetCode = true
                  }else{
                      this.$message.warning(res.message)
                  }
              })
            }
          })
      },
      countDowm () {
          var self = this
          clearInterval(this.timer)
          this.timer = setInterval(function () {
          if (self.hour === 0) {
              if (self.minute === 0 && self.second === 1){
                self.isGetCode = false
              }
              if (self.minute !== 0 && self.second === 0) {
                self.second = 59
                self.minute -= 1
              } else if (self.minute === 0 && self.second === 0) {
                self.second = 0
                // self.$emit('countDowmEnd', true)
                clearInterval(self.timer)
              } else {
                self.second -= 1
              }
              
          } else {
              if (self.minute !== 0 && self.second === 0) {
              self.second = 59
              self.minute -= 1
              } else if (self.minute === 0 && self.second === 0) {
              self.hour -= 1
              self.minute = 59
              self.second = 59
              } else {
              self.second -= 1
              }
          }
          }, 1000)
      },
      formatNum (num) {
        return num < 10 ? '0' + num : '' + num
      },
      handleSubmit () {
        
        if (this.customActiveKey === 'tab1') {
          let validateArr =[]
          if(this.isOpenCode){
            validateArr = ['username', 'password','passcode']
          }else{
            validateArr = ['username', 'password']
          }
          this.form.validateFields(validateArr, { force: true }, (err,values) => {
            if (!err) {
              if(this.isOpenCode){
                validateLoginCode({username:values.username,code:values.passcode}).then(res=>{
                  if(res.code == 200){
                    this.$refs.verify.show()
                  }else{
                    this.$message.warning(res.message)
                  }
                })
              }else{
                this.$refs.verify.show()
              }
            }
          })
        } else {
          this.form.validateFields(['mobile', 'captcha'], { force: true }, (err, values) => {
            if (!err) {
              let loginParams = {}
              this.loginBtn = true
              loginParams.mobile = values.mobile
              loginParams.captcha = values.captcha
              // loginParams.remember_me = values.rememberMe
              this.PhoneLogin(loginParams).then((res) => {
                this.departConfirm(res)
              }).catch((err) => {
                this.requestFailed(err)
              })
            }
          })
        }
      },
      login ({captchaVerification}) {
        let validateArr =[]
          if(this.isOpenCode){
            validateArr = ['username', 'password','passcode']
          }else{
            validateArr = ['username', 'password']
          }
        this.form.validateFields(validateArr, { force: true }, (err, values) => {
          if (!err) {
            let loginParams = {}
            this.loginBtn = true
            loginParams.username = values.username
            loginParams.password = values.password
            // loginParams.remember_me = values.rememberMe
            loginParams.captchaVerification = captchaVerification
            this.Login(loginParams).then((res) => {
              this.departConfirm(res)
            }).catch((err) => {
              this.requestFailed(err)
            })
          }
        })
      },
      useDingtalk(){
        this.showLoginBox = false
        SSO.useDingtalk()
      },
      getCaptcha (e) {
        e.preventDefault()
        let that = this
        this.form.validateFields(['mobile'], { force: true }, (err, values) => {
            if (!values.mobile) {
              that.cmsFailed(that.$t('m.system.login.verify.mobile'))
            } else if (!err) {
              this.state.smsSendBtn = true
              let interval = window.setInterval(() => {
                if (that.state.time-- <= 0) {
                  that.state.time = 60
                  that.state.smsSendBtn = false
                  window.clearInterval(interval)
                }
              }, 1000)

              const hide = this.$message.loading(this.$t('m.system.login.other.captchaSend'), 0)
              let smsParams = {}
              smsParams.mobile = values.mobile
              smsParams.smsmode = '0'
              postAction(YchConstant.PREFIX_SYSTEM + '/sms', smsParams)
                .then(res => {
                  if (!res.success) {
                    setTimeout(hide, 0)
                    this.cmsFailed(res.message)
                  }
                  //console.log(res)
                  setTimeout(hide, 500)
                })
                .catch(err => {
                  setTimeout(hide, 1)
                  clearInterval(interval)
                  that.state.time = 60
                  that.state.smsSendBtn = false
                  this.requestFailed(err)
                })
            }
          }
        )
      },
      loginSuccess () {
        this.$router.push({ path: '/' }).catch(err => {})
        this.messageUtil.success(this.$t('m.system.login.other.welcomeback'), this.$t('m.system.login.other.welcome'))
      },
      cmsFailed (err) {
        this.messageUtil.warning(err, this.$t('m.system.login.other.loginFailed'))
      },
      requestFailed (err) {
        this.messageUtil.warning(((err.response || {}).data || {}).message || err.message || this.$t('m.system.login.other.loginError'), this.$t('m.system.login.other.loginFailed'))
        this.loginBtn = false
      },
      validateMobile (rule, value, callback) {
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
          callback()
        } else {
          callback(this.$t('m.system.login.verify.mobile'))
        }

      },
      departConfirm (res) {
        if (res.success) {
          let multi_depart = res.result.multi_depart
          //0:无部门 1:一个部门 2:多个部门
          if (multi_depart == 0) {
            this.loginSuccess()
            this.messageUtil.warning(this.$t('m.system.login.other.noDept'), this.$t('m.common.label.prompt'))
          } else if (multi_depart == 2) {
            this.departVisible = true
            this.currentUsername = this.form.getFieldValue('username')
            this.departList = res.result.departs
          } else {
            this.loginSuccess()
          }
        } else {
          this.requestFailed(res)
          this.Logout()
        }
      },
      departOk () {
        if (!this.departSelected) {
          this.validate_status = 'error'
          return false
        }
        let obj = {
          orgCode: this.departSelected,
          username: this.form.getFieldValue('username')
        }
        putAction(YchConstant.PREFIX_SYSTEM + '/user/selectDepart', obj).then(res => {
          if (res.success) {
            const userInfo = res.result.userInfo
            store.commit('SET_INFO', userInfo)
            this.departClear()
            this.loginSuccess()
          } else {
            this.requestFailed(res)
            this.Logout().then(() => {
              this.departClear()
            })
          }
        })
      },
      departClear () {
        this.departList = []
        this.departSelected = ''
        this.currentUsername = ''
        this.departVisible = false
        this.validate_status = ''
      },
      departChange (value) {
        this.validate_status = 'success'
        this.departSelected = value
      },
      getRouterData () {
        this.$nextTick(() => {
          if (this.$route.params.username) {
            this.form.setFieldsValue({
              'username': this.$route.params.username
            })
          }
        })
      },
    }
  }
</script>


<style lang="less" scoped>
  .login-container {
    display: flex;
    align-items: center;
    position: relative;
    width: 100%;
    height: 100%;
    margin: 0 auto;
    background: url("../../../assets/login-background.jpg")
    0 bottom repeat-x #049ec4;
    animation: animate-cloud 20s linear infinite;
  }
  .login-weaper {
    margin: 0 auto;
    width: 1000px;
    box-shadow: -4px 5px 10px rgba(0, 0, 0, 0.4);
    .ant-input-group__append {
      border: none;
    }
  }

  .login-left,
  .login-border {
    position: relative;
    min-height: 500px;
    align-items: center;
    display: flex;
  }
  .login-left {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    justify-content: center;
    flex-direction: column;
    background-color: #409EFF;
    color: #fff;
    float: left;
    width: 50%;
    position: relative;
  }
  .login-left .img {
    width: 140px;
  }

  .login-left .title {
    margin-top: 60px;
    text-align: center;
    color: #fff;
    font-weight: 600;
    letter-spacing: 2px;
    font-size: 25px;
  }

  .login-border {
    border-left: none;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    color: #fff;
    background-color: #fff;
    width: 50%;
    float: left;
    box-sizing: border-box;
  }
  .login-main {
    margin: 0 auto;
    width: 70%;
    box-sizing: border-box;
  }
  .login-main > h3 {
    margin-bottom: 20px;
  }
  .login-main > p {
    color: #76838f;
  }

  .login-submit {
    width: 100%;
    height: 45px;
    border: 1px solid #409EFF;
    background: none;
    font-size: 18px;
    letter-spacing: 2px;
    font-weight: 300;
    color: #409EFF;
    cursor: pointer;
    margin-top: 10px;
    font-family: "neo";
    transition: 0.25s;
  }

  /deep/ .login-form {
    margin: 10px 0;
    
    i {
      color: #333;
    }
    .ant-form-item__content {
      width: 100%;
    }
    .ant-form-item {
      margin-bottom: 18px;
    }
    .ant-input {
      input {
        padding-bottom: 10px;
        text-indent: 5px;
        background: transparent;
        border: none;
        border-radius: 0;
        color: #333;
        border-bottom: 1px solid rgb(235, 237, 242);
      }
      .ant-input__prefix {
        i {
          padding: 0 5px;
          font-size: 16px !important;
        }
      }
    }
  }

  .login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;
    color: #898d90;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, .2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color .3s;

      &  :hover {
        color: #1890ff;
      }
    }
    .back-btn {
      float: right;
    }
  }
  .code-btn-box:hover, .code-btn-box:focus{
      color: rgba(0, 0, 0, 1) !important;
      border-color: #d9d9d9 !important;

    }
    .text-color{
      color: #597ef7 !important;
    }
</style>
